﻿using MapleLeaf.Application.CookBook;
using MapleLeaf.Application.CookBook.Parameter;
using MapleLeaf.Core;
using MapleLeaf.Core.Cache.Redis;
using MapleLeaf.Core.Dto;
using MapleLeaf.Core.Handler;
using MapleLeaf.WebApi.CookBook.Controllers.Dto;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace MapleLeaf.WebApi.CookBook.Controllers {
    /// <summary>
    /// 
    /// </summary>
    public class AuthController : ApiBaseController {
        private readonly IRedisHelper _redisHelper;
        private readonly AuthClient  _authClient;
        /// <summary>
        /// 构造函数
        /// </summary>
        public AuthController(IRedisHelper handler, AuthClient authClient) {
            _redisHelper = handler;
            _authClient = authClient;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<CaptchaDto>> Captcha() {
            var captcha = CaptchaHelper.GenerateCaptcha(height: 40);

            // 重置流位置（确保从头读取）
            captcha.ImageStream.Seek(0, SeekOrigin.Begin);

            // 转换为字节数组
            byte[] imageBytes = captcha.ImageStream.ToArray();

            // 转换为 Base64
            string base64String = Convert.ToBase64String(imageBytes);

            // 添加前缀用于 HTML 显示
            string htmlImage = $"data:image/png;base64,{base64String}";

            var dto = new CaptchaDto() {
                CaptchaKey = CommonHandle.GenerateUniqueId(),
                CaptchaBase64 = htmlImage
            };
            await _redisHelper.SetStringAsync(dto.CaptchaKey, $"{captcha.Answer}", TimeSpan.FromSeconds(30));
            return Success(dto);
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<AuthenticationToken>> Login([FromForm]LoginParameter parameter) {
            var userInfo = await _authClient.Login(parameter);
            var authResult = JwtHandler.CreateToken(userInfo);
            return Success(authResult);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ApiResult LogOut() {
            //var userInfo = await _authClient.Login(parameter);
            //var authResult = JwtHandler.CreateToken(userInfo);
            return Success();
        }
    }
}
